/* 
 * drag 1.0
 * create by tony@jentian.com
 * date 2015-08-18
 * 拖动滑块
 */

(function($) {
    $(".handler handler_bg").on('click',function(ev) {
       var oEvent=ev||event;
       console.log("x坐标是:"+oEvent.clientX+",y坐标是:"+oEvent.clientY);
    });

    function drawing(action) {
        $("#BombBox").hide();
        //获取验证码信息
        $.ajax({
            type: "GET",
            url: "/uweb/service/yzm/getYZM",
            async: false,
            success: function (result) {
                console.log(result.imgInfo.key);
                $("#BombBox .yzmMainImgSub").css({"background-image":"url(\"" + (result.imgPathPrefix + result.imgInfo.heiImg) + "\")"});
                $("#BombBox .yzmCutImg").css({
                    "background": "url(\"" + (result.imgPathPrefix + result.imgInfo.cutImg) + "\") no-repeat",
                    "top": result.imgInfo.y + "px"
                });
                $("#BombBox #drag").drag({key: result.imgInfo.key, action: action});
            }
        });
        $("#BombBox").show();
    }

    $.fn.yzm = function (action) {
        $("#BombBox").remove();
        this.after('<div id="BombBox" class="BombBox">\n' +
            '        <div class="yzmImgDiv">\n' +
            '            <div class="yzmMainImg">\n' +
            '               <div class="yzmMainImgSub" style="background-position: -130px -60px;"></div>\n' +
            '               <div class="yzmMainImgSub" style="background-position: -260px -60px;"></div>\n' +
            '               <div class="yzmMainImgSub" style="background-position: -130px 0;"></div>\n' +
            '               <div class="yzmMainImgSub" style="background-position: -260px 0;"></div>\n' +
            '            </div>\n' +
            '            <div class="yzmCutImg" id="xy_img"></div>\n' +
            '        </div>\n' +
            '        <div id="drag"></div>\n' +
            '    </div>');

        drawing(action);
    }

    $.fn.drag = function(options) {
        var x, drag = this, isMove = false, defaults = {key:"",action:null};
        var options = $.extend(defaults, options);
        //添加背景，文字，滑块
        var html = '<div class="drag_bg"></div>'+
                   '<div class="drag_text" onselectstart="return false;" unselectable="on">按住左边滑块，拖动完成上方拼图</div>'+
                   '<div class="handler handler_bg"></div>';
        this.html(html);

        var handler = this.find(".handler");
        var drag_bg = this.find('.drag_bg');
        var text = this.find('.drag_text');
        var $xy_img = $("#xy_img");

        $xy_img.css({'left':0});

        var maxWidth = this.width() - handler.width() - 2;  //能滑动的最大间距

        //鼠标按下时候的x轴的位置
        var moveStart = function(e) {
            $xy_img.show();
            isMove = true;
            switch (e.type) {
                case "mousedown": x = e.pageX - parseInt(handler.css('left'), 10); break;
                case "touchstart" : x = event.touches[0].pageX - parseInt(handler.css('left'), 10);
            }
        };

        //鼠标指针在上下文移动时，移动距离大于0小于最大间距，滑块x轴位置等于鼠标移动距离
        var moveEvent = function(e) {
            if (!isMove) {
                return;
            }
            var _x;
            switch (e.type) {
                case "mousemove": _x = e.pageX - x; break;
                case "touchmove" : _x = event.touches[0].pageX - x;
            }
            console.log("move" + _x + ", maxWidth" + maxWidth);
            if(isMove){
                if (_x > 0 && _x <= maxWidth) {
                    $xy_img.css({'left': _x});
                    handler.css({'left': _x});
                    drag_bg.css({'width': _x});
                }
            }
        };
        var moveEnd = function(e) {
            if (!isMove) {
                return;
            }
            isMove = false;
            var _x;
            switch (e.type) {
                case "mouseup": _x = e.pageX - x; break;
                case "touchend" : _x = event.changedTouches[0].pageX - x; break;
            }
            console.log("move" + _x + ", maxWidth" + maxWidth);
            //验证码校验
            $.ajax({ //校验
                type:"POST",
                url:"/uweb/service/yzm/check",
                dataType:"JSON",
                async: false,
                data:{point:_x,key:defaults.key},
                success:function(result){
                    if(result['state'] == 0 ) {
                        for(var i=1; 4>=i; i++){
                            $xy_img.animate({left:_x-(40-10*i)},50);
                            $xy_img.animate({left:_x+2*(40-10*i)},50,function(){
                                $xy_img.css({'left':result['correctPoint']});
                            });
                        }
                        handler.css({'left': maxWidth});
                        drag_bg.css({'width': maxWidth});
                        $xy_img.removeClass('xy_img_bord');
                        dragOk();
                        if (defaults.action !== undefined && defaults.action !== null) {
                            defaults.action(result['key']);
                        }
                    } else if (result['state'] === 100) {
                        drawing(defaults.action);
                        toast(result['desc'])
                    } else {
                        $xy_img.css({'left': 0});
                        handler.css({'left': 0});
                        drag_bg.css({'width': 0});
                        dragFailed();
                    }
                }
            });
        };
        this.find(".handler").mousedown(moveStart);
        this.find(".handler").on('touchstart', moveStart);
        $(document).mousemove(moveEvent).mouseup(moveEnd);
        $(document).on('touchmove', moveEvent);
        $(document).on('touchend', moveEnd);
//
//        var handler = drag.find('.handler');
//        var drag_bg = drag.find('.drag_bg');
//        var text = drag.find('.drag_text');
//        var maxWidth = drag.width() - handler.width();  //能滑动的最大间距
//
//        //鼠标按下时候的x轴的位置
//        handler.mousedown(function(e){
//            $xy_img.show();
//            isMove = true;
//            x = e.pageX - parseInt(handler.css('left'), 10);
//        });
//
//        var $xy_img = $("#xy_img");
//
//        //鼠标指针在上下文移动时，移动距离大于0小于最大间距，滑块x轴位置等于鼠标移动距离
//        $(document).mousemove(function(e){
//            var _x = e.pageX - x;
//            if(isMove){
//                $xy_img.css({'left': _x});
//                if(_x > 0 && _x <= maxWidth){
//                    handler.css({'left': _x});
//                    drag_bg.css({'width': _x});
//                }else if(_x > maxWidth || x < 0){  //鼠标指针移动距离达到最大时清空事件
//                    handler.unbind('mousedown');
//                    $(document).unbind('mousemove');
//                    $(document).unbind('mouseup');
//                }
//            }
//        }).mouseup(function(e){
//            isMove = false;
//            var _x = e.pageX - x;
//
//            $.ajax({ //校验
//                type:"POST",
//                url:"check",
//                dataType:"JSON",
//                async: false,
//                data:{point:_x+1,key:defaults.key},
//                success:function(result){
//                    if(result['state'] == 0 ) {
//                        for(var i=1; 4>=i; i++){
//                            $xy_img.animate({left:_x-(40-10*i)},50);
//                            $xy_img.animate({left:_x+2*(40-10*i)},50,function(){
//                                $xy_img.css({'left':result['data']});
//                            });
//                        }
//                        handler.css({'left': maxWidth});
//                        drag_bg.css({'width': maxWidth});
//                        $xy_img.removeClass('xy_img_bord');
//                        dragOk();
//                    } else {
//                        $xy_img.css({'left': 0});
//                        handler.css({'left': 0});
//                        drag_bg.css({'width': 0});
//                        dragFailed();
//                        handler.unbind('mousedown');
//                        $(document).unbind('mousemove');
//                        $(document).unbind('mouseup');
////                        if(_x <= maxWidth){ //鼠标松开时，如果没有达到最大距离位置，滑块就返回初始位置
////                            handler.css({'left': 0});
////                            drag_bg.css({'width': 0});
////                        }
//                    }
//                },
//                beforeSend:function(){
//                    //$(".text-c").children('td').html('<i style="color: lightseagreen">加载中...</i>');
//                }
//            });
//
//        });
//
        function dragFailed(){
            text.text('验证失败：拖动滑块将悬浮图像正确拼合');
        }

        //清空事件
        function dragOk(key){
            handler.removeClass('handler_bg').addClass('handler_ok_bg');
            text.text('验证通过');
            drag.css({'color': '#fff'});
            handler.unbind('mousedown');
            $(document).unbind('mousemove');
            $(document).unbind('mouseup');
            $("#BombBox").delay(1500).hide(0);
        }
    };
})(jQuery);